package org.cy.websocket.stomp.integration;

import org.cy.websocket.stomp.StompWebSocket;
import org.cy.websocket.stomp.messaging.Message;
import org.cy.websocket.stomp.messaging.StompDecoder;
import org.cy.websocket.stomp.messaging.StompEncoder;

import java.nio.charset.StandardCharsets;

/**
 * Created in 2021-05-10 22:44
 *
 * @author cao.yong
 */
public abstract class AbstractWebSocket implements StompWebSocket {

    private final StompEncoder encoder = new StompEncoder();
    private final StompDecoder decoder = new StompDecoder();

    protected Message<byte[]> decodeMessage(Object data, boolean isBinary) {
        Message<byte[]> decodeMessage;
        if (isBinary) {
            decodeMessage = this.decoder.decode((byte[]) data);
        } else {
            decodeMessage = this.decoder.decode(data.toString().getBytes(StandardCharsets.UTF_8));
        }
        return decodeMessage;
    }

    protected byte[] encodeMessage(Message<byte[]> message) {
        return this.encoder.encode(message);
    }
}
